package controller

import (
	"strconv"

	"gostore/dao"
	"gostore/model"
	"gostore/router"

	com "gostore/common"

	"github.com/gin-gonic/gin"
)

type SystemUserLevelControllerT struct {
	BaseControllerT
}

var SystemUserLevelController = SystemUserLevelControllerT{}

func (o SystemUserLevelControllerT) List(c *gin.Context) {
	req := new(dao.ReqQuerySystemUserLevel)

	err := c.ShouldBindQuery(req)
	if err != nil {
		com.Err(c, 503, "错误的参数")
		return
	}

	userList, count, err := dao.SystemUserLevelDao.SystemUserLevelList(req)
	if err != nil {
		com.Err(c, 503, "查询失败")
		return
	}

	mdata := make(map[string]interface{}, 0)
	mdata["list"] = userList
	mdata["count"] = count
	com.Ok(c, mdata)
}

func (o SystemUserLevelControllerT) Create(c *gin.Context) {

	sUserLevel := new(model.SystemUserLevel)

	err := c.ShouldBind(&sUserLevel)

	if err != nil {
		com.Err(c, 503, "传上来的内容有错误")
		return
	}

	err = dao.SystemUserLevelDao.Save(sUserLevel)
	if err != nil {
		com.Err(c, 503, "创建失败")
		return
	}
	com.Ok(c, sUserLevel)
}

func (o SystemUserLevelControllerT) Update(c *gin.Context) {
	id := c.Param("id")
	levelId, err := strconv.Atoi(id)
	if err != nil {
		com.Err(c, 503, "错误的参数id")
		return
	}
	sUserLevel := new(model.SystemUserLevel)

	err = c.ShouldBind(&sUserLevel)

	if err != nil {
		com.Err(c, 503, "传上来的内容有错误")
		return
	}
	sUserLevel.Id = levelId

	err = dao.SystemUserLevelDao.Save(sUserLevel)
	if err != nil {
		com.Err(c, 503, "创建失败")
		return
	}
	com.Ok(c, sUserLevel)
}

func (o SystemUserLevelControllerT) AddNewRoutes() {
	router.AddRouteGroup("api/systemUserLevels", []router.Route{
		router.Route{
			Method:  router.MGet,
			Path:    "",
			Handler: o.List,
		},
	})
	router.AddRouteGroup("api/systemUserLevels", []router.Route{
		router.Route{
			Method:  router.MPost,
			Path:    "",
			Handler: o.Create,
		},
	})
	router.AddRouteGroup("api/systemUserLevels", []router.Route{
		router.Route{
			Method:  router.MPut,
			Path:    "/:id",
			Handler: o.Update,
		},
	})
}
